import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ChartEChartsOption } from '@delon/chart/chart-echarts';
import { ModalHelper, _HttpClient } from '@delon/theme';
import * as moment from 'moment';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { zip } from 'rxjs';
import { finalize } from 'rxjs/operators';

export interface itemTrafficTreeNode {
  source_id: string;
  item_id: string;
  source: {};
  ctm_item_click_uv?: number;
  ctm_item_click_uv_compare?: number;
  item_cart_uv?: number;
  item_cart_uv_compare?: number;
  order_uv?: number;
  order_uv_compare?: number;
  ctm_order_view_rate?: number;
  ctm_order_view_rate_compare?: number;
  level?: number;
  expand?: boolean;
  children?: itemTrafficTreeNode[];
  parent?: itemTrafficTreeNode;
}

@Component({
  selector: 'app-business-ware-analysis',
  templateUrl: './ware-analysis.component.html'
})
export class BusinessWareAnalysisComponent implements OnInit {
  constructor(private http: _HttpClient, private modal: ModalHelper, private route: ActivatedRoute, private cdr: ChangeDetectorRef) {}
  q: { dateType: number; dateVal: string; shopId: number; itemId: number } = {
    shopId: 0,
    itemId: 0,
    dateType: 0,
    dateVal: ''
  };
  dateTypeOptions = [
    { index: 1, text: '昨日' },
    { index: 2, text: '近7天' },
    { index: 3, text: '近30天' },
    { index: 4, text: '日' },
    { index: 5, text: '月' }
  ];
  compareText = '';
  statistics_date = '';
  loading = true;
  itemOverView = [];
  factors = {};
  itemTrend = [];
  skuIndicate = [];
  listOfMapData: itemTrafficTreeNode[] = [];
  mapOfExpandedData: { [source_id: string]: itemTrafficTreeNode[] } = {};

  option: ChartEChartsOption | undefined;

  ngOnInit(): void {
    let params = this.route.snapshot.queryParams;
    console.log(params);
    this.q.shopId = Number(params['shopId']);
    this.q.itemId = Number(params['itemId']);
    this.q.dateType = Number(params['dateType']);
    this.q.dateVal = params['dateVal'];
    this.statistics_date = params['dateVal'];
    if (this.q.dateType == 1) {
      this.compareText = '较前一日';
    } else if (this.q.dateType == 2) {
      this.compareText = '较前7日';
    } else if (this.q.dateType == 3) {
      this.compareText = '较前30日';
    } else if (this.q.dateType == 5) {
      this.compareText = '较前一月';
    } else if (this.q.dateType == 4) {
      this.compareText = '较前一日';
    }
    this.loadDataFromServer();
  }

  loadDataFromServer(): void {
    this.loading = true;
    zip(this.http.get(`api/item/overview`, this.q), this.http.get(`api/item/trend`, this.q), this.http.get(`api/item/traffic`, this.q))
      .pipe(
        finalize(() => {
          this.cdr.detectChanges();
        })
      )
      .subscribe(([itemOverview, itemTrend, itemTraffic]: [NzSafeAny, NzSafeAny, NzSafeAny]) => {
        // @ts-ignore
        if (itemOverview.data) {
          // @ts-ignore
          this.itemOverView = [itemOverview.data];
          this.skuIndicate = itemOverview.data['sku_indicator_list'];
        }
        this.factors = itemTrend.data.factors;
        this.itemTrend = itemTrend.data.list;
        let [dateAxis, y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12, y13] = [[], [], [], [], [], [], [], [], [], [], [], [], [], []];
        for (let k in this.itemTrend) {
          let v = this.itemTrend[k];
          // @ts-ignore
          dateAxis.unshift(moment(v['date']).format('YYYY-MM-DD'));
          y1.unshift(v['ctm_item_view_cnt']);
          // @ts-ignore
          y2.unshift((v['ctm_item_view_rate_new'] * 100).toFixed(2));
          y3.unshift(v['ctm_item_click_uv']);
          y4.unshift(v['ctm_item_click_cnt']);
          y5.unshift(v['item_cart_uv']);
          y6.unshift(v['item_cart_cnt']);
          // @ts-ignore
          y7.unshift((v['ctm_cart_view_rate'] * 100).toFixed(2));
          y8.unshift(v['order_uv']);
          y9.unshift(v['item_order_cnt']);
          // @ts-ignore
          y10.unshift((v['ctm_order_view_rate'] * 100).toFixed(2));
          y11.unshift(v['item_verified_uv']);
          y12.unshift(v['item_verified_cnt']);
          y13.unshift(v['item_wishlist_cnt']);
        }
        // 处理折线图
        this.option = {
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: dateAxis
          },
          yAxis: [
            {
              type: 'value',
              name: '数值',
              min: 0,
              interval: 3000
            },
            {
              type: 'value',
              name: '百分比',
              min: 0,
              interval: 5,
              axisLabel: {
                formatter: '{value} %'
              }
            }
          ],
          legend: {
            data: [
              '曝光量',
              '曝光点击率',
              '访客数',
              '浏览量',
              '加购人数',
              '加购件数',
              '加购率',
              '下单人数',
              '下单件数',
              '下单转化率',
              '订单确认人数',
              '订单确认件数',
              '心愿单(收藏)数'
            ],
            selected: {
              曝光量: true,
              曝光点击率: false,
              访客数: false,
              浏览量: false,
              加购人数: false,
              加购件数: false,
              加购率: false,
              下单人数: false,
              下单件数: false,
              下单转化率: false,
              订单确认人数: false,
              订单确认件数: false,
              '心愿单(收藏)数': false
            }
          },
          series: [
            {
              name: '曝光量',
              data: y1,
              type: 'line',
              smooth: true,
              yAxisIndex: 0
            },
            {
              name: '曝光点击率',
              data: y2,
              type: 'line',
              smooth: true,
              yAxisIndex: 0
            },
            {
              name: '访客数',
              data: y3,
              type: 'line',
              smooth: true,
              yAxisIndex: 0
            },
            {
              name: '浏览量',
              data: y4,
              type: 'line',
              smooth: true,
              yAxisIndex: 0
            },
            {
              name: '加购人数',
              data: y5,
              type: 'line',
              smooth: true,
              yAxisIndex: 0
            },
            {
              name: '加购件数',
              data: y6,
              type: 'line',
              smooth: true,
              yAxisIndex: 0
            },
            {
              name: '加购率',
              data: y7,
              type: 'line',
              smooth: true,
              yAxisIndex: 1
            },
            {
              name: '下单人数',
              data: y8,
              type: 'line',
              smooth: true,
              yAxisIndex: 0
            },
            {
              name: '下单人数',
              data: y8,
              type: 'line',
              smooth: true,
              yAxisIndex: 0
            },
            {
              name: '下单件数',
              data: y9,
              type: 'line',
              smooth: true,
              yAxisIndex: 0
            },
            {
              name: '下单转化率',
              data: y10,
              type: 'line',
              smooth: true,
              yAxisIndex: 1
            },
            {
              name: '订单确认人数',
              data: y11,
              type: 'line',
              smooth: true,
              yAxisIndex: 0
            },
            {
              name: '订单确认件数',
              data: y12,
              type: 'line',
              smooth: true,
              yAxisIndex: 0
            },
            {
              name: '心愿单(收藏)数',
              data: y13,
              type: 'line',
              smooth: true,
              yAxisIndex: 0
            }
          ]
        };
        this.listOfMapData = itemTraffic.data;
        if (this.listOfMapData) {
          this.listOfMapData.forEach(item => {
            this.mapOfExpandedData[item.source_id] = this.convertTreeToList(item);
          });
        }
        this.loading = false;
      });
  }

  dateTypeChange(value: number) {
    this.q.dateVal = '';
    let yesterday = moment().subtract(1, 'days').format('YYYY-MM-DD');
    if (value == 1) {
      this.statistics_date = yesterday;
      this.q.dateVal = this.statistics_date;
      this.loadDataFromServer();
      this.compareText = '较前一日';
    } else if (value == 2) {
      this.statistics_date = `${moment().subtract(7, 'days').format('YYYY-MM-DD')}~${yesterday}`;
      this.q.dateVal = this.statistics_date;
      this.loadDataFromServer();
      this.compareText = '较前7日';
    } else if (value == 3) {
      this.statistics_date = `${moment().subtract(30, 'days').format('YYYY-MM-DD')}~${yesterday}`;
      this.q.dateVal = this.statistics_date;
      this.loadDataFromServer();
      this.compareText = '较前30日';
    } else if (value == 5) {
      this.compareText = '较前一月';
    } else if (value == 4) {
      this.compareText = '较前一日';
    }
  }

  datePickerChange(value: any) {
    if (this.q.dateType == 4) {
      this.q.dateVal = moment(value).format('yyyy-MM-DD');
    } else if (this.q.dateType == 5) {
      this.q.dateVal = moment(value).format('yyyy-MM');
    }
    this.statistics_date = this.q.dateVal;
    this.loadDataFromServer();
  }

  collapse(array: itemTrafficTreeNode[], data: itemTrafficTreeNode, $event: boolean): void {
    if (!$event) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.source_id === d.source_id)!;
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root: itemTrafficTreeNode): itemTrafficTreeNode[] {
    const stack: itemTrafficTreeNode[] = [];
    const array: itemTrafficTreeNode[] = [];
    const hashMap = {};
    stack.push({ ...root, level: 0, expand: false });

    while (stack.length !== 0) {
      const node = stack.pop()!;
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({ ...node.children[i], level: node.level! + 1, expand: false, parent: node });
        }
      }
    }

    return array;
  }

  visitNode(node: itemTrafficTreeNode, hashMap: { [source_id: string]: boolean }, array: itemTrafficTreeNode[]): void {
    if (!hashMap[node.source_id]) {
      hashMap[node.source_id] = true;
      array.push(node);
    }
  }
}
